package com.test;

import java.net.HttpURLConnection;
import java.net.URLDecoder;

import com.yint.io.http.EasyHttp;
import com.yint.io.http.response.Response;

public class WeiXinHttpHelper {

	private static final String BASE_URL = "https://api.weixin.qq.com/cgi-bin";

	// 获取access_token
	private static final String TOKEN_URL = BASE_URL + "/token?grant_type=client_credential&appid=%s&secret=%s";

	// 创建自定义菜单
	private static final String CREATE_MENU_URL = BASE_URL + "/menu/create?access_token=%s";

	/**
	 * 请求access_token
	 * 
	 * @param appId1
	 * @param appSecret
	 * @return 服务器返回字符串
	 * @throws Exception
	 */
	public static String getAccessToken(String appId, String appSecret) throws Exception {
		Response response = null;
		try {
			EasyHttp easyHttp = new EasyHttp();
			easyHttp.setConnectTimeout(5000);
			response = easyHttp.getSyn(String.format(TOKEN_URL, appId, appSecret));
			if (HttpURLConnection.HTTP_OK == response.getCode()) {
				return URLDecoder.decode(response.body().toString(), "UTF-8");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	/**
	 * 创建菜单
	 * 
	 * @param menu
	 * @param accessToken
	 * @return
	 * @throws Exception
	 */
	public static String createMenu(String menu, String accessToken) throws Exception {
		Response response = null;
		try {
			EasyHttp easyHttp = new EasyHttp();
			easyHttp.setConnectTimeout(5000);
			response = easyHttp.postSyn(String.format(CREATE_MENU_URL, accessToken), menu, "application/x-www-form-urlencoded");
			if (HttpURLConnection.HTTP_OK == response.getCode()) {
				return URLDecoder.decode(response.body().toString(), "UTF-8");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}
}
